package tut.fileLock.sharedLock;

import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class SharedLockTest {

    public static void main(String[] args) throws Exception {
      //  test3(true, true); // ok
        test3(false, true); // ok
       // test3(true, false); // ok
       // test3(false, false); // ok
        // => test3: どうでもいい  (^ ^)
    }

    public static void test3(boolean shared, boolean trylock) throws Exception {
        RandomAccessFile fis = new RandomAccessFile("/var/adptg/test.txt", "rw");
        FileChannel fc = fis.getChannel();
        FileLock fl = null;
        if (trylock)
            fl = fc.tryLock(0, 2, shared);
        else
            fl = fc.lock(0, fc.size(), shared);

        if(fl ==null) {
        	 if (trylock)
                 fl = fc.tryLock(3, 5, shared);
             else
                 fl = fc.lock(4, 5, shared);
        }
        fis.writeBytes("mhbbn");
        fl.release();
    }
}

// ca 2 thang cung exclusive deu duoc mien la vi tri lock ko chong len nhau